import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import App from './App.vue'
import store from './store'
import Home from './views/Home.vue'
import Dashboard from './views/Dashboard.vue'
import LoginPage from './views/Auth/LoginPage.vue'
import RegisterPage from './views/Auth/RegisterPage.vue'
import UserList from './views/UserList.vue'
import UserForm from './views/UserForm.vue'
import QuestionBank from './views/QuestionBank.vue'
import QuestionForm from './views/QuestionForm.vue'
import ExamList from './views/ExamList.vue'
import ExamForm from './views/ExamForm.vue'
import ExamDetail from './views/ExamDetail.vue'

// 创建路由
const routes = [
    { path: '/', name: 'home', component: Home },
    { path: '/login', name: 'login', component: LoginPage, meta: { guest: true } },
    { path: '/register', name: 'register', component: RegisterPage, meta: { guest: true } },
    { path: '/dashboard', name: 'dashboard', component: Dashboard, meta: { requiresAuth: true } },
    { path: '/users', name: 'users', component: UserList },
    { path: '/users/create', name: 'create-user', component: UserForm },
    { path: '/users/edit/:id', name: 'edit-user', component: UserForm },
    { path: '/questions', name: 'questions', component: QuestionBank },
    { path: '/questions/new', name: 'create-question', component: QuestionForm },
    { path: '/questions/edit/:id', name: 'edit-question', component: QuestionForm, props: true },
    { path: '/exams', name: 'exams', component: ExamList },
    { path: '/exams/new', name: 'create-exam', component: ExamForm },
    { path: '/exams/edit/:id', name: 'edit-exam', component: ExamForm, props: true },
    { path: '/exams/:id', name: 'exam-detail', component: ExamDetail, props: true },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const loggedIn = localStorage.getItem('token')

    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!loggedIn) {
            next('/login')
        } else {
            next()
        }
    } else if (to.matched.some(record => record.meta.guest)) {
        if (loggedIn) {
            next('/dashboard')
        } else {
            next()
        }
    } else {
        next()
    }
})

// 创建Vue应用
const app = createApp(App)

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.use(router)
app.use(store)
app.use(ElementPlus)
app.mount('#app') 